/**
 * Created by wangcan on 2017-10-31.
 */
var async = require('async');
var moment = require('moment');
var schedule = require("node-schedule");
var messageUtil = require('../../common/utils/messageUtil');
var toolUtil = require('../../common/utils/toolUtil');
var mtOrder = mongoose.model('mtOrder');
var User = mongoose.model('user');
var Regions = mongoose.model('masterData_Regions');
var Community = mongoose.model('community');
var userService = require('./../userService');
var Question = mongoose.model('question');
var Goods = mongoose.model('goods');
var UserInvitation = mongoose.model('user_invitation');
var RoleApply = mongoose.model('user_role_apply');

// 大使佣金一览---ForTest
exports.ambCommisionDayListForTest = function (body, size, index, callback){

    var parallelLimitCount = 5; // 限制并行个数
    var startDate = null;
    var endDate = null;

    if (!body.startdate) {
        var msg = {"message": '日期参数不能为空!'};
        return callback(msg, null);
    }
    var tempDate = body.startdate;

    var option = [];
    option.push({"$match": {"type": 4}});
    option.push({"$match": {"isValid" : true}});
    option.push({"$match": {"startDateTime": {$lt: new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").format())}}});
    option.push({"$match": {"endDateTime": {$gt: new Date(moment(tempDate, "YYYY-MM-DD").format())}}});
    // if (body && body.mobilePhone) option.push({"$match": {"phone": new RegExp(body.mobilePhone)}});
    // if (body && body.nickName) option.push({"$match": {"name": new RegExp(body.nickName)}});
    option.push({"$group": {"_id": {"userId":"$user"}, count: {$sum: 1}}});

    // 返回数据集合
    var ambCommArr = [];
    var ambUserObjArr = [];
    var ambUserArr = [];
    async.series([
        // 分页
        function (callbackInner) {
            // option.push({"$group": {_id: "$userId", count: {$sum: 1}}});
            option.push({"$sort": {"_id": -1}});
            RoleApply.aggregate(option, function (err, countRes) {
                if (err) {
                    logger.error("没有数据!");
                    callbackInner(err, null);
                } else {
                    if (body.mobilePhone || body.nickName) {
                        var opt = {};
                        if (body.mobilePhone) opt.mobilePhone = new RegExp(body.mobilePhone);
                        if (body.nickName) opt.nickName = new RegExp(body.nickName);
                        User.find(opt, '_id nickName mobilePhone').sort({'_id': -1}).exec(function (err, userRes) {
                            if (err) {
                                logger.error("没有大使数据!");
                                callbackInner(err, null);
                            } else {
                                if (userRes == undefined || userRes == null) {
                                    logger.info({"message": '没有大使数据'});
                                    callbackInner({"message": '没有大使数据'}, null);
                                } else {
                                    for (var i = 0, length = countRes.length; i < length; i++) {
                                        for (var j = 0, resSize = userRes.length; j < resSize; j++) {
                                            if (countRes[i]._id.userId.toString() == userRes[j].id) {
                                                ambUserObjArr.push(userRes[j]);
                                                break;
                                            }
                                        }
                                    }
                                    var temp = {};
                                    if (ambUserObjArr != null && ambUserObjArr.length > 0 ) {
                                        temp = {count:ambUserObjArr.length, page: Math.ceil(ambUserObjArr.length/(size ? size : 1)), code: 0};
                                    } else {
                                        // "用户在该日期中不是大使！";
                                        temp = {count:ambUserObjArr.length, page: Math.ceil(ambUserObjArr.length/(size ? size : 1)), code: 1};
                                    }
                                    callbackInner(null, temp);
                                }
                            }
                        });
                    } else {
                        var temp = {};
                        if (countRes != null && countRes.length > 0) {
                            for (var i = 0, length = countRes.length; i < length; i++) {
                                ambUserObjArr.push(countRes[i]);
                            }
                            temp = {count:countRes.length, page: Math.ceil(countRes.length/(size ? size : 1)), code: 0};
                        } else {
                            temp = {count:countRes.length, page: Math.ceil(countRes.length/(size ? size : 1)), code: 2};
                        }
                        callbackInner(null, temp);
                    }
                }
            });
        },
        function (callbackInner) {
            // 查询大使用户数据
            // option[option.length - 1] = {"$sort": {"_id": -1}};
            // if (size != -1) {
            //     option.push({"$skip": index});
            //     option.push({"$limit": size});
            // }
            // RoleApply.aggregate(option, function (err, ambUsersRes) {
            //     if (err) {
            //         callbackInner(err, null);
            //     } else {
            //         if (ambUsersRes == undefined || ambUsersRes == null) {
            //             var msg = {
            //                 "message": '没有大使数据'
            //             };
            //             logger.info(msg);
            //             callbackInner(msg, null);
            //         } else {
            if (size != -1) {
                if (ambUserObjArr != null && ambUserObjArr.length > 0) {
                    for (var k = index; k < size + index; k++) {
                        ambUserArr.push(ambUserObjArr[k]);
                        if (ambUserObjArr.length == k + 1) {
                            break;
                        }
                    }
                }
            } else {
                if (ambUserObjArr != null && ambUserObjArr.length > 0) {
                    for (var k = 0, length = ambUserObjArr.length; k < length; k++) {
                        ambUserArr.push(ambUserObjArr[k]);
                    }
                }
            }

            async.eachSeries(ambUserArr, function (ambUserObj, callbackTempInner) {
                startDate = moment(tempDate, "YYYY-MM-DD").format();
                endDate = moment(startDate, "YYYY-MM-DD").add(1, "days").format();
                var userId = null;
                if (body.mobilePhone || body.nickName) {
                    userId = ambUserObj._id;
                } else {
                    userId = ambUserObj._id.userId;
                    // userId = ambUserObj._id.userId.toString();
                }
                async.parallelLimit([
                    // 查询大使信息
                    function (callbackInnerInner) {
                        User.findOne({_id: userId},'_id nickName mobilePhone', function (err, ambUserResult) {
                            if (err) {
                                logger.error("没有此用户!");
                                callbackInnerInner({"message": "没有此用户!"}, null);
                            } else {
                                callbackInnerInner(null, ambUserResult);
                            }
                        })
                    },
                    // 总佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "communityCommissionUser": "$communityCommissionUser",
                                "communityCommission": "$communityCommission",
                                "selfPurchaseUser": "$selfPurchaseUser",
                                "selfPurchase": "$selfPurchase",
                                "inviterCommissionUser": "$inviterCommissionUser",
                                "inviterCommission": "$inviterCommission",
                                "shareCommissionUser": "$shareCommissionUser",
                                "shareCommission": "$shareCommission"
                            }, count: {$sum: 1}}}
                        ], function (err, totalCommissionRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var totalCommResult = 0;
                                if (totalCommissionRes != null && totalCommissionRes.length > 0) {
                                    for (var i = 0, length = totalCommissionRes.length; i < length; i++) {
                                        if (totalCommissionRes[i]._id.shareCommissionUser != null
                                            && totalCommissionRes[i]._id.shareCommissionUser.toString() == userId.toString()) {
                                            totalCommResult += totalCommissionRes[i]._id.shareCommission;
                                        }
                                        if (totalCommissionRes[i]._id.selfPurchaseUser != null
                                            && totalCommissionRes[i]._id.selfPurchaseUser.toString() == userId.toString()) {
                                            totalCommResult += totalCommissionRes[i]._id.selfPurchase;
                                        }
                                        if (totalCommissionRes[i]._id.communityCommissionUser != null
                                            && totalCommissionRes[i]._id.communityCommissionUser.toString() == userId.toString()) {
                                            totalCommResult += totalCommissionRes[i]._id.communityCommission;
                                        }
                                        if (totalCommissionRes[i]._id.inviterCommissionUser != null
                                            && totalCommissionRes[i]._id.inviterCommissionUser.toString() == userId.toString()) {
                                            totalCommResult += totalCommissionRes[i]._id.inviterCommission;
                                        }
                                    }
                                }
                                callbackInnerInner(null, totalCommResult.toFixed(2));
                            }
                        });
                    },
                    // 分享订单佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"shareCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "shareCommissionUser": "$shareCommissionUser",
                                "shareCommission": "$shareCommission"
                            }, count: {$sum: 1}}}
                        ], function (err, shareCommissionRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var shareCommResult = 0;
                                if (shareCommissionRes != null && shareCommissionRes.length > 0) {
                                    for (var i = 0, length = shareCommissionRes.length; i < length; i++) {
                                        if (shareCommissionRes[i]._id.shareCommission) {
                                            shareCommResult += shareCommissionRes[i]._id.shareCommission;
                                        }
                                    }
                                }
                                callbackInnerInner(null, shareCommResult.toFixed(2));
                            }
                        });
                    },
                    // 自购订单佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"selfPurchaseUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "selfPurchaseUser": "$selfPurchaseUser",
                                "selfPurchase": "$selfPurchase"
                            }, count: {$sum: 1}}}
                        ], function (err, selfPurchaseRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var selfPurCommResult = 0;
                                if (selfPurchaseRes != null && selfPurchaseRes.length > 0) {
                                    for (var i = 0, length = selfPurchaseRes.length; i < length; i++) {
                                        if (selfPurchaseRes[i]._id.selfPurchase) {
                                            selfPurCommResult += selfPurchaseRes[i]._id.selfPurchase;
                                        }
                                    }
                                }
                                callbackInnerInner(null, selfPurCommResult.toFixed(2));
                            }
                        });
                    },
                    // 小区订单佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"communityCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "communityCommissionUser": "$communityCommissionUser",
                                "communityCommission": "$communityCommission"
                            }, count: {$sum: 1}}}
                        ], function (err, commCommRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var commCommResult = 0;
                                if (commCommRes != null && commCommRes.length > 0) {
                                    for (var i = 0, length = commCommRes.length; i < length; i++) {
                                        if (commCommRes[i]._id.communityCommission) {
                                            commCommResult += commCommRes[i]._id.communityCommission;
                                        }
                                    }
                                }
                                callbackInnerInner(null, commCommResult.toFixed(2));
                            }
                        });
                    },
                    // 被邀请大使订单佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"inviterCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "inviterCommissionUser": "$inviterCommissionUser",
                                "inviterCommission": "$inviterCommission"
                            }, count: {$sum: 1}}}
                        ], function (err, invitedCommRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var invitedCommResult = 0;
                                if (invitedCommRes != null && invitedCommRes.length > 0) {
                                    for (var i = 0, length = invitedCommRes.length; i < length; i++) {
                                        if (invitedCommRes[i]._id.inviterCommission) {
                                            invitedCommResult += invitedCommRes[i]._id.inviterCommission;
                                        }
                                    }
                                }
                                callbackInnerInner(null, invitedCommResult.toFixed(2));
                            }
                        });
                    },
                    // 总订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, totalOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var orderCounts = 0;
                                if (totalOrders != null && totalOrders.length > 0) {
                                    orderCounts = totalOrders[0].count;
                                }
                                callbackInnerInner(null, orderCounts);
                            }
                        });
                    },
                    // 已成团订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"newGroupOrderStatus": "0"}},
                            // {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, groupOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var groupOrderCounts = 0;
                                if (groupOrders != null && groupOrders.length > 0) {
                                    groupOrderCounts = groupOrders[0].count;
                                }
                                callbackInnerInner(null, groupOrderCounts);
                            }
                        });
                    },
                    // 未成团订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"newGroupOrderStatus": {$in: ["1", "2"]}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, unGroupOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var unGroupOrderCounts = 0;
                                if (unGroupOrders != null && unGroupOrders.length > 0) {
                                    unGroupOrderCounts = unGroupOrders[0].count;
                                }
                                callbackInnerInner(null, unGroupOrderCounts);
                            }
                        });
                    },
                    // 已退款订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": "100"}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, refundOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var refundOrderCounts = 0;
                                if (refundOrders != null && refundOrders.length > 0) {
                                    refundOrderCounts = refundOrders[0].count;
                                }
                                callbackInnerInner(null, refundOrderCounts);
                            }
                        });
                    },
                    // 分享订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"shareCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, shareOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var shareOrderCounts = 0;
                                if (shareOrders != null && shareOrders.length > 0) {
                                    shareOrderCounts = shareOrders[0].count;
                                }
                                callbackInnerInner(null, shareOrderCounts);
                            }
                        });
                    },
                    // 自购订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"selfPurchaseUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, selfPurchaseOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var selfPurchaseOrderCounts = 0;
                                if (selfPurchaseOrders != null && selfPurchaseOrders.length > 0) {
                                    selfPurchaseOrderCounts = selfPurchaseOrders[0].count;
                                }
                                callbackInnerInner(null, selfPurchaseOrderCounts);
                            }
                        });
                    },
                    // 小区订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"communityCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, commCommOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var commCommOrderCounts = 0;
                                if (commCommOrders != null && commCommOrders.length > 0) {
                                    commCommOrderCounts = commCommOrders[0].count;
                                }
                                callbackInnerInner(null, commCommOrderCounts);
                            }
                        });
                    },
                    // 被邀请大使订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match:{"inviterCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, invitedAmbOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var invitedAmbOrderCounts = 0;
                                if (invitedAmbOrders != null && invitedAmbOrders.length > 0) {
                                    invitedAmbOrderCounts = invitedAmbOrders[0].count;
                                }
                                callbackInnerInner(null, invitedAmbOrderCounts);
                            }
                        });
                    }
                ], parallelLimitCount, function(err, parallelRes) {
                    var tempRow = {};
                    // 大使id
                    tempRow.ambUserId = parallelRes[0].id;
                    // 时间
                    tempRow.orderDate = tempDate.substr(0, 10).toString();
                    // 大使昵称
                    tempRow.ambNickName = parallelRes[0].nickName;
                    // 大使手机号
                    tempRow.ambMobilePhone = parallelRes[0].mobilePhone;
                    // 总佣金
                    tempRow.totalCommission = parallelRes[1];
                    // 分享订单佣金
                    tempRow.shareCommission = parallelRes[2];
                    // 自购订单佣金
                    tempRow.selfPurComm = parallelRes[3];
                    // 小区订单佣金
                    tempRow.communityComm = parallelRes[4];
                    // 被邀请大使订单佣金
                    tempRow.invitedComm = parallelRes[5];
                    // 总订单数
                    tempRow.totalOrders = parallelRes[6];
                    // 已成团订单数
                    tempRow.groupOrders = parallelRes[7];
                    // 未成团订单数
                    tempRow.unGroupOrders = parallelRes[8];
                    // 已退款订单数
                    tempRow.refundOrders = parallelRes[9];
                    // 分享订单数
                    tempRow.shareOrders = parallelRes[10];
                    // 自购订单数
                    tempRow.selfPurOrders = parallelRes[11];
                    // 小区订单数
                    tempRow.communityOrders = parallelRes[12];
                    // 被邀请大使订单数
                    tempRow.invitedAmbOrders = parallelRes[13];
                    ambCommArr.push(tempRow);

                    callbackTempInner(false);
                });
            }, function (err) {
                callbackInner(false);
            });
                    // }
                // }
            // });
        },
    ], function (err, ambCommResults) {
        if (err) {
            callback(err, null);
        } else {
            ambCommResults[1] = ambCommArr;
            callback(null, ambCommResults);
        }
    });
};

// 指定日期是否是小区大使
exports.appointDateIsModerator = function (userId, tempDate, callback) {
    var startDate = new Date(moment(tempDate, "YYYY-MM-DD").format());
    var endDate = new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").format());
    // var option = {"user": userId, "startDateTime": {$lt: appointDate}, "endDateTime": {$gt: appointDate}};
    var option = {"user": userId, "startDateTime": {$lt: endDate}, "endDateTime": {$gt: startDate}};
    RoleApply.findOne(option, {"status" : 1, "_id" : 0}, function (err, result) {
        if(result) {
            logger.debug("状态: " + result.status);
            callback(null, true);
        } else {
            callback(null, false);
        }
    });
};

// 大使佣金一览---根据订单佣金归属人查大使数据
exports.ambCommisionDayList = function (body, size, index, callback){

    var parallelLimitCount = 5; // 限制并行个数
    var startDate = null;
    var endDate = null;

    if (!body.startdate) {
        var msg = {"message": '日期参数不能为空!'};
        return callback(msg, null);
    }
    var tempDate = body.startdate;

    var opt4Group = [];
    opt4Group.push({$match: {"isValid": true}});
    opt4Group.push({$match: {"order_time": {$gte: new Date(moment(tempDate, "YYYY-MM-DD").format()), $lt: new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").format())}}});
    opt4Group.push({$match:{$or:[
        {"shareCommissionUser": {$ne: null}},
        {"selfPurchaseUser": {$ne: null}},
        {"communityCommissionUser": {$ne: null}},
        {"inviterCommissionUser": {$ne: null}}
    ]}});
    opt4Group.push({$group:{"_id": {
        "comUserId": "$communityCommissionUser",
        "selfPurUserId": "$selfPurchaseUser",
        "invitedUserId": "$inviterCommissionUser",
        "shareUserId": "$shareCommissionUser"}
    }});
    opt4Group.push({"$sort": {"_id": -1}});

    // 返回数据集合
    var ambCommArr = [];
    var ambUserObjArr = [];
    var ambUserArr = [];
    async.series([
        // 分页
        function (callbackInner) {
            mtOrder.aggregate(opt4Group, function (err, groupRes) {
                if (err) {
                    logger.error("没有数据!");
                    callbackInner(err, null);
                } else {
                    if (groupRes == undefined || groupRes == null) {
                        logger.info({"message": '没有归属人数据'});
                        callbackInner({"message": '没有归属人数据'}, null);
                    } else {
                        var tempArr = [];
                        // 将所有归属人Id存入临时数组
                        for (var i = 0, length = groupRes.length; i < length; i++) {
                            if (groupRes[i]._id.comUserId) {
                                tempArr.push(groupRes[i]._id.comUserId);
                            }
                            if (groupRes[i]._id.selfPurUserId) {
                                tempArr.push(groupRes[i]._id.selfPurUserId);
                            }
                            if (groupRes[i]._id.invitedUserId) {
                                tempArr.push(groupRes[i]._id.invitedUserId);
                            }
                            if (groupRes[i]._id.shareUserId) {
                                tempArr.push(groupRes[i]._id.shareUserId);
                            }
                        }
                        // 数组去重
                        var noneRepArr = toolUtil.arrayDislodgeRepeat(tempArr);

                        // var tempAmbUserArr = [];
                        // var appointDate = new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").format());
                        // 判断归属人是否小区大使，是则存入新数组
                        // async.eachSeries(noneRepArr, function (tempUserId, callbackEachSeriesInner) {
                            // var startDate = new Date(moment(tempDate, "YYYY-MM-DD").format());
                            // var endDate = new Date(moment(tempDate, "YYYY-MM-DD").add(1, "days").format());
                            // // var option = {"user": userId, "startDateTime": {$lt: appointDate}, "endDateTime": {$gt: appointDate}};
                            // var option = {"user": tempUserId, "startDateTime": {$lt: endDate}, "endDateTime": {$gt: startDate}};
                            // RoleApply.findOne(option, {"status" : 1, "_id" : 0}, function (err, result) {
                            //     if(result) {
                            //         logger.debug("状态: " + result.status);
                            //         tempAmbUserArr.push(tempUserId);
                            //         callbackEachSeriesInner(false);
                            //         // callback(null, true);
                            //     } else {
                            //         // callback(null, false);
                            //         callbackEachSeriesInner(false);
                            //     }
                            // });
                        // for (var i = 0, length = noneRepArr.length; i < length; i++) {
                        // async.eachSeries(noneRepArr, function (tempUserId, callbackEachSeriesInner) {
                        //     exports.appointDateIsModerator(tempUserId, tempDate, function (tempErr, isShareModerator) {
                        //         if (err) {
                        //             callbackEachSeriesInner(false);
                        //             // callbackInner(err, null);
                        //         } else {
                        //             if (isShareModerator) {
                        //                 tempAmbUserArr.push(tempUserId);
                        //                 callbackEachSeriesInner(false);
                        //             }
                        //         }
                        //     });
                        // // }
                        // }, function (err5) {
                        //     callbackInner(err5, null);
                        // });

                        if (body.mobilePhone || body.nickName) {
                            var opt = {};
                            if (body.mobilePhone) opt.mobilePhone = new RegExp(body.mobilePhone);
                            if (body.nickName) opt.nickName = new RegExp(body.nickName);
                            User.find(opt, '_id nickName mobilePhone').sort({'_id': -1}).exec(function (err, userRes) {
                                if (err) {
                                    logger.error("没有大使数据!");
                                    callbackInner(err, null);
                                } else {
                                    if (userRes == undefined || userRes == null) {
                                        logger.info({"message": '没有大使数据'});
                                        callbackInner({"message": '没有大使数据'}, null);
                                    } else {
                                        for (var i = 0, length = noneRepArr.length; i < length; i++) {
                                            for (var j = 0, resSize = userRes.length; j < resSize; j++) {
                                                if (noneRepArr[i].toString() == userRes[j].id) {
                                                    ambUserObjArr.push(userRes[j]);
                                                    break;
                                                }
                                            }
                                        }
                                        var temp = {count:ambUserObjArr.length, page: Math.ceil(ambUserObjArr.length/(size ? size : 1)), code: 0};
                                        callbackInner(null, temp);
                                    }
                                }
                            });
                        } else {
                            for (var i = 0, length = noneRepArr.length; i < length; i++) {
                                ambUserObjArr.push(noneRepArr[i]);
                            }
                            var temp = {count:ambUserObjArr.length, page: Math.ceil(ambUserObjArr.length/(size ? size : 1)), code: 0};
                            callbackInner(null, temp);
                        }
                    }
                }
            });
        },
        function (callbackInner) {
            if (size != -1) {
                if (ambUserObjArr != null && ambUserObjArr.length > 0) {
                    for (var k = index; k < size + index; k++) {
                        ambUserArr.push(ambUserObjArr[k]);
                        if (ambUserObjArr.length == k + 1) {
                            break;
                        }
                    }
                }
            } else {
                if (ambUserObjArr != null && ambUserObjArr.length > 0) {
                    for (var k = 0, length = ambUserObjArr.length; k < length; k++) {
                        ambUserArr.push(ambUserObjArr[k]);
                    }
                }
            }

            async.eachSeries(ambUserArr, function (ambUserObj, callbackTempInner) {
                startDate = moment(tempDate, "YYYY-MM-DD").format();
                endDate = moment(startDate, "YYYY-MM-DD").add(1, "days").format();
                var userId = null;
                if (body.mobilePhone || body.nickName) {
                    userId = ambUserObj._id;
                } else {
                    userId = ambUserObj;
                    // userId = ambUserObj._id.userId.toString();
                }
                async.parallelLimit([
                    // 查询大使信息
                    function (callbackInnerInner) {
                        User.findOne({_id: userId},'_id nickName mobilePhone', function (err, ambUserResult) {
                            if (err) {
                                logger.error("没有此用户!");
                                callbackInnerInner({"message": "没有此用户!"}, null);
                            } else {
                                callbackInnerInner(null, ambUserResult);
                            }
                        })
                    },
                    // 总佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "communityCommissionUser": "$communityCommissionUser",
                                "communityCommission": "$communityCommission",
                                "selfPurchaseUser": "$selfPurchaseUser",
                                "selfPurchase": "$selfPurchase",
                                "inviterCommissionUser": "$inviterCommissionUser",
                                "inviterCommission": "$inviterCommission",
                                "shareCommissionUser": "$shareCommissionUser",
                                "shareCommission": "$shareCommission"
                            }, count: {$sum: 1}}}
                        ], function (err, totalCommissionRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var totalCommResult = 0;
                                if (totalCommissionRes != null && totalCommissionRes.length > 0) {
                                    for (var i = 0, length = totalCommissionRes.length; i < length; i++) {
                                        if (totalCommissionRes[i]._id.shareCommissionUser != null
                                            && totalCommissionRes[i]._id.shareCommissionUser.toString() == userId.toString()) {
                                            totalCommResult += totalCommissionRes[i]._id.shareCommission;
                                        }
                                        if (totalCommissionRes[i]._id.selfPurchaseUser != null
                                            && totalCommissionRes[i]._id.selfPurchaseUser.toString() == userId.toString()) {
                                            totalCommResult += totalCommissionRes[i]._id.selfPurchase;
                                        }
                                        if (totalCommissionRes[i]._id.communityCommissionUser != null
                                            && totalCommissionRes[i]._id.communityCommissionUser.toString() == userId.toString()) {
                                            totalCommResult += totalCommissionRes[i]._id.communityCommission;
                                        }
                                        if (totalCommissionRes[i]._id.inviterCommissionUser != null
                                            && totalCommissionRes[i]._id.inviterCommissionUser.toString() == userId.toString()) {
                                            totalCommResult += totalCommissionRes[i]._id.inviterCommission;
                                        }
                                    }
                                }
                                callbackInnerInner(null, totalCommResult.toFixed(2));
                            }
                        });
                    },
                    // 分享订单佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"shareCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "shareCommissionUser": "$shareCommissionUser",
                                "shareCommission": "$shareCommission"
                            }, count: {$sum: 1}}}
                        ], function (err, shareCommissionRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var shareCommResult = 0;
                                if (shareCommissionRes != null && shareCommissionRes.length > 0) {
                                    for (var i = 0, length = shareCommissionRes.length; i < length; i++) {
                                        if (shareCommissionRes[i]._id.shareCommission) {
                                            shareCommResult += shareCommissionRes[i]._id.shareCommission;
                                        }
                                    }
                                }
                                callbackInnerInner(null, shareCommResult.toFixed(2));
                            }
                        });
                    },
                    // 自购订单佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"selfPurchaseUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "selfPurchaseUser": "$selfPurchaseUser",
                                "selfPurchase": "$selfPurchase"
                            }, count: {$sum: 1}}}
                        ], function (err, selfPurchaseRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var selfPurCommResult = 0;
                                if (selfPurchaseRes != null && selfPurchaseRes.length > 0) {
                                    for (var i = 0, length = selfPurchaseRes.length; i < length; i++) {
                                        if (selfPurchaseRes[i]._id.selfPurchase) {
                                            selfPurCommResult += selfPurchaseRes[i]._id.selfPurchase;
                                        }
                                    }
                                }
                                callbackInnerInner(null, selfPurCommResult.toFixed(2));
                            }
                        });
                    },
                    // 小区订单佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"communityCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "communityCommissionUser": "$communityCommissionUser",
                                "communityCommission": "$communityCommission"
                            }, count: {$sum: 1}}}
                        ], function (err, commCommRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var commCommResult = 0;
                                if (commCommRes != null && commCommRes.length > 0) {
                                    for (var i = 0, length = commCommRes.length; i < length; i++) {
                                        if (commCommRes[i]._id.communityCommission) {
                                            commCommResult += commCommRes[i]._id.communityCommission;
                                        }
                                    }
                                }
                                callbackInnerInner(null, commCommResult.toFixed(2));
                            }
                        });
                    },
                    // 被邀请大使订单佣金
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"inviterCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "inviterCommissionUser": "$inviterCommissionUser",
                                "inviterCommission": "$inviterCommission"
                            }, count: {$sum: 1}}}
                        ], function (err, invitedCommRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var invitedCommResult = 0;
                                if (invitedCommRes != null && invitedCommRes.length > 0) {
                                    for (var i = 0, length = invitedCommRes.length; i < length; i++) {
                                        if (invitedCommRes[i]._id.inviterCommission) {
                                            invitedCommResult += invitedCommRes[i]._id.inviterCommission;
                                        }
                                    }
                                }
                                callbackInnerInner(null, invitedCommResult.toFixed(2));
                            }
                        });
                    },
                    // 总订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, totalOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var orderCounts = 0;
                                if (totalOrders != null && totalOrders.length > 0) {
                                    orderCounts = totalOrders[0].count;
                                }
                                callbackInnerInner(null, orderCounts);
                            }
                        });
                    },
                    // 已成团订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"newGroupOrderStatus": "0"}},
                            // {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, groupOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var groupOrderCounts = 0;
                                if (groupOrders != null && groupOrders.length > 0) {
                                    groupOrderCounts = groupOrders[0].count;
                                }
                                callbackInnerInner(null, groupOrderCounts);
                            }
                        });
                    },
                    // 未成团订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"newGroupOrderStatus": {$in: ["1", "2"]}}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, unGroupOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var unGroupOrderCounts = 0;
                                if (unGroupOrders != null && unGroupOrders.length > 0) {
                                    unGroupOrderCounts = unGroupOrders[0].count;
                                }
                                callbackInnerInner(null, unGroupOrderCounts);
                            }
                        });
                    },
                    // 已退款订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {$or: [
                                {"shareCommissionUser": userId},
                                {"selfPurchaseUser": userId},
                                {"communityCommissionUser": userId},
                                {"inviterCommissionUser": userId}
                            ]}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": "100"}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, refundOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var refundOrderCounts = 0;
                                if (refundOrders != null && refundOrders.length > 0) {
                                    refundOrderCounts = refundOrders[0].count;
                                }
                                callbackInnerInner(null, refundOrderCounts);
                            }
                        });
                    },
                    // 分享订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"shareCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, shareOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var shareOrderCounts = 0;
                                if (shareOrders != null && shareOrders.length > 0) {
                                    shareOrderCounts = shareOrders[0].count;
                                }
                                callbackInnerInner(null, shareOrderCounts);
                            }
                        });
                    },
                    // 自购订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"selfPurchaseUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, selfPurchaseOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var selfPurchaseOrderCounts = 0;
                                if (selfPurchaseOrders != null && selfPurchaseOrders.length > 0) {
                                    selfPurchaseOrderCounts = selfPurchaseOrders[0].count;
                                }
                                callbackInnerInner(null, selfPurchaseOrderCounts);
                            }
                        });
                    },
                    // 小区订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"communityCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, commCommOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var commCommOrderCounts = 0;
                                if (commCommOrders != null && commCommOrders.length > 0) {
                                    commCommOrderCounts = commCommOrders[0].count;
                                }
                                callbackInnerInner(null, commCommOrderCounts);
                            }
                        });
                    },
                    // 被邀请大使订单数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match:{"inviterCommissionUser": userId}},
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"isValid": true}},
                            {$match: {"status": {$ne: "100"}}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, invitedAmbOrders) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var invitedAmbOrderCounts = 0;
                                if (invitedAmbOrders != null && invitedAmbOrders.length > 0) {
                                    invitedAmbOrderCounts = invitedAmbOrders[0].count;
                                }
                                callbackInnerInner(null, invitedAmbOrderCounts);
                            }
                        });
                    }
                ], parallelLimitCount, function(err, parallelRes) {
                    var tempRow = {};
                    // 大使id
                    tempRow.ambUserId = parallelRes[0].id;
                    // 时间
                    tempRow.orderDate = tempDate.substr(0, 10).toString();
                    // 大使昵称
                    tempRow.ambNickName = parallelRes[0].nickName;
                    // 大使手机号
                    tempRow.ambMobilePhone = parallelRes[0].mobilePhone;
                    // 总佣金
                    tempRow.totalCommission = parallelRes[1];
                    // 分享订单佣金
                    tempRow.shareCommission = parallelRes[2];
                    // 自购订单佣金
                    tempRow.selfPurComm = parallelRes[3];
                    // 小区订单佣金
                    tempRow.communityComm = parallelRes[4];
                    // 被邀请大使订单佣金
                    tempRow.invitedComm = parallelRes[5];
                    // 总订单数
                    tempRow.totalOrders = parallelRes[6];
                    // 已成团订单数
                    tempRow.groupOrders = parallelRes[7];
                    // 未成团订单数
                    tempRow.unGroupOrders = parallelRes[8];
                    // 已退款订单数
                    tempRow.refundOrders = parallelRes[9];
                    // 分享订单数
                    tempRow.shareOrders = parallelRes[10];
                    // 自购订单数
                    tempRow.selfPurOrders = parallelRes[11];
                    // 小区订单数
                    tempRow.communityOrders = parallelRes[12];
                    // 被邀请大使订单数
                    tempRow.invitedAmbOrders = parallelRes[13];
                    ambCommArr.push(tempRow);

                    callbackTempInner(false);
                });
            }, function (err) {
                callbackInner(false);
            });
        },
    ], function (err, ambCommResults) {
        if (err) {
            callback(err, null);
        } else {
            ambCommResults[1] = ambCommArr;
            callback(null, ambCommResults);
        }
    });
};